<template>
  <div class="register">
    <div class="col-left"></div>
    <div class="register-box">
      <div class="title">后台管理系统</div>
      <div class="form-box">

        <el-form :model="userInfo" status-icon ref="userInfo" :rules="rules">

          <el-form-item prop="userName">
            <el-input type="text" v-model="userInfo.userName" autocomplete="off" placeholder="输入昵称(字母数字汉字下划线1-10位)"></el-input>
          </el-form-item>

          <el-form-item prop="email">
            <el-input type="text" v-model="userInfo.email" autocomplete="off" placeholder="输入邮箱"></el-input>
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input type="password" v-model="userInfo.password" show-password autocomplete="off" placeholder="输入密码(6-16位)"></el-input>
          </el-form-item>

          <el-form-item prop="repassword">
            <el-input type="password" v-model="userInfo.repassword" show-password autocomplete="off" placeholder="输入确认密码"></el-input>
          </el-form-item>
  
        
          <el-form-item prop="validcode">
            <el-row :gutter="15">
              <el-col :span="14">
                <el-input v-model="userInfo.validcode" autocomplete="off" placeholder="输入6位数字验证码"></el-input>
              </el-col>
              <el-col :span="10">
                <el-button class="fr" :disabled="isSend"  @click="sendCode">{{text}}</el-button>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item class="form-group">
             <el-button class="register-btn" type="primary" @click="submitForm('userInfo')">注册</el-button>
          </el-form-item>

          <div class="clearfix login-text">
            <span class="fr" @click="goPage('B_Login')">已有账号，登录</span>
          </div>

        </el-form>

      </div>
    </div>
  </div>
</template>

<script>
import '@/assets/less/b_register.less'
  export default {
    name: 'B_Register',
    data(){
      return{
        userInfo: {
          userName:'',
          email: '',
          password: '',
          repassword: '',
          validcode: ''
        },

        //验证表单规则
        rules: {
          userName: [
             { validator: this.validNickName, trigger: 'blur' }
          ],

          email: [
             { validator: this.validEmail, trigger: 'blur' }
          ],

          password: [
            { validator: this.validPassword, trigger: 'blur' }
          ],

          repassword: [
            { validator: this.validRepassword, trigger: 'blur' }
          ],

          validcode: [
            { validator: this.validCode, trigger: 'blur' }
          ]

        },

        text: '获取验证码',
        isSend: false,

        //验证码的id
        codeId: ''
      }
    },

    methods:{
      goPage(n){
        this.$router.push({name: n});
      },
      //获取验证码
      sendCode() {
        //验证邮箱格式是否正确
        let reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
        if (!reg.test(this.userInfo.email)) {
          return;
        }

        let time = 5;
        this.text = `${time}s后重新发送`;
        this.isSend = true;

        let timer = setInterval(() => {
          if (time == 0) {
            clearInterval(timer);
            timer = null;
            this.text = '获取验证码';
            this.isSend = false;
            
          } else {
            time--;
            this.text = `${time}s后重新发送`;
          }
        }, 1000)

        //发起获取验证码请求
        this.axios({
          method: 'POST',
          url: this.baseUrl + '/email',
          data: {
            email: this.userInfo.email
          }
        }).then(res => {
          console.log('res ==> ', res);
          if (res.data.code == 1010) {
            this.codeId = res.data.cid;
            this.$message({
              message: res.data.msg,
              type: 'success'
            });
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch(err => {
          this.$message.error(res.data.msg);
          console.log('err ==> ', err);
        })
      },

      //验证昵称
      validNickName(rule, value, callback){
        if (!value) {
          return callback(new Error('昵称不能为空'));
        }
        setTimeout(() => {
          let reg = /^[\w\u4e00-\u9fa5]{1,10}$/;
          if (!reg.test(value)) {
            callback(new Error('昵称格式不正确'));
          } else {
            callback();
          }
        }, 400);
      },

      //验证邮箱
      validEmail(rule, value, callback) {
        if (!value) {
          return callback(new Error('邮箱不能为空'));
        }
        setTimeout(() => {
          let reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
          if (!reg.test(value)) {
            callback(new Error('邮箱格式不正确'));
          } else {
            callback();
          }
        }, 400);
      },

      //验证密码(首字符为字母, 字母数字_组合, 6-16位)
      validPassword(rule, value, callback) {
        if (!value) {
          return callback(new Error('密码不能为空'));
        }
        setTimeout(() => {
          let reg = /^[A-Za-z]\w{5,15}$/;
          if (!reg.test(value)) {
            callback(new Error('密码必须以字母开头，可包含字母数字_'));
          } else {
            callback();
          }
        }, 400);
      },

      //验证确认密码
      validRepassword(rule, value, callback) {
        if (!value) {
          return callback(new Error('确认密码不能为空'));
        }
        setTimeout(() => {
          if (value != this.userInfo.password) {
            callback(new Error('两次密码不一致'));
          } else {
            callback();
          }
        }, 400);
      },

      //验证验证码
      validCode(rule, value, callback) {
        if (!value) {
          return callback(new Error('验证码不能为空'));
        }
        setTimeout(() => {
          let reg = /^\d{6}$/;
          if (!reg.test(value)) {
            callback(new Error('验证码必须为6位数字'));
          } else {
            callback();
          }
        }, 400);
      },

      // 注册
      submitForm(formName) {
        //判断是否获取验证码
        if (!this.codeId) {
          this.$message.warning('请获取验证码');
          return;
        }

        this.$refs[formName].validate((valid) => {
          if (!valid) {
            return false;
          }

          //发起注册请求
          console.log('发起注册请求');
          this.axios({
            method: 'POST',
            url: this.baseUrl + '/b_register',
            data: {
              // 管理员昵称
              userName: this.userInfo.userName,
              //管理员邮箱
              email: this.userInfo.email,
              //管理员密码
              password: this.userInfo.password,
              //验证码
              validcode: this.userInfo.validcode,
              // 验证码id
              codeId: this.codeId
            }
          }).then(res => {
            console.log('res ==> ', res);
            if(res.data.code == 1000){
              this.$message({
                message: `${res.data.msg}，准备跳转到登录页。`,
                type: 'success'
              });
              setTimeout(() => {
                this.$router.push({name: 'B_Login'})
              }, 2000);
            }else{
              this.$message({
                message: res.data.msg,
                type: 'error'
              });
            }
          }).catch(err => {
            console.log('err ==> ', err);
          })

        });
      },
      
    }
  }
</script>

